import requests
import re
import argparse
import time
import datetime

def get_current_date():
    """获取系统当前日期，返回年、月、日三元组"""
    now = datetime.datetime.now()
    return now.year, now.month, now.day

def generate_file_names(year, month, day=None):
    """生成Markdown文件名列表"""
    year_month = f"{year}-{month:02d}"
    file_names = []
    
    if day is None:
        # 只提供了年月，生成该月所有可能的日期
        for day in range(1, 32):  # 最多31天，后续会过滤不存在的日期
            for hour in range(24):
                for minute in [0, 30]:
                    file_name = f"{year_month}/{day:02d}日{hour:02d}时{minute:02d}分.md"
                    file_names.append(file_name)
    else:
        # 提供了完整日期，只生成当天的文件
        for hour in range(24):
            for minute in [0, 30]:
                file_name = f"{year_month}/{day:02d}日{hour:02d}时{minute:02d}分.md"
                file_names.append(file_name)
    
    return file_names

def find_latest_file(file_names):
    base_url = "https://raw.githubusercontent.com/sharkDoor/vpn-free-nodes/master/node-list/"
    file_names.reverse()  # 从最新的时间开始尝试
    
    print(f"开始查找最新文件，共{len(file_names)}个候选...")
    found = False
    
    for idx, file_name in enumerate(file_names):
        url = base_url + file_name
        attempt_num = idx + 1
        
        try:
            print(f"尝试请求 [{attempt_num}/{len(file_names)}]: {file_name}")
            start_time = time.time()
            response = requests.get(url)
            elapsed = time.time() - start_time
            
            if response.status_code == 200:
                print(f"✅ 找到有效文件 (耗时: {elapsed:.2f}s): {file_name}")
                return url, file_name
            else:
                print(f"❌ 文件不存在 (状态码: {response.status_code}, 耗时: {elapsed:.2f}s): {file_name}")
                
        except requests.RequestException as e:
            print(f"⚠️ 请求出错: {str(e)} - {file_name}")
            continue
            
        # 添加短暂延迟避免请求过于频繁
        time.sleep(0.5)
    
    print(f"❌ 未找到有效文件")
    return None, None

def download_file(url, file_name):
    local_filename = file_name.replace("/", "_")  # 替换斜杠以适应本地文件名
    try:
        print(f"开始下载文件: {local_filename}")
        response = requests.get(url)
        
        if response.status_code == 200:
            with open(local_filename, 'w', encoding='utf-8') as f:
                f.write(response.text)
            print(f"✅ 下载完成: {local_filename}")
        else:
            print(f"❌ 下载失败，状态码: {response.status_code}")
            
    except requests.RequestException as e:
        print(f"⚠️ 下载过程发生错误: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='下载最新的Markdown文件（自动获取系统日期或通过参数指定）')
    parser.add_argument('--date', type=str, help='指定日期范围，格式为YYYY-MM（年月）或YYYY-MM-DD（完整日期）')
    args = parser.parse_args()

    if args.date:
        parts = args.date.split('-')
        if len(parts) == 2:  # YYYY-MM
            year = int(parts[0])
            month = int(parts[1])
            day = None  # 生成该月所有日期
            print(f"已指定日期范围: {year}年{month}月")
        elif len(parts) == 3:  # YYYY-MM-DD
            year = int(parts[0])
            month = int(parts[1])
            day = int(parts[2])
            print(f"已指定完整日期: {year}年{month}月{day}日")
        else:
            print("日期格式错误，请使用YYYY-MM或YYYY-MM-DD格式")
            exit(1)
    else:
        # 未提供参数，使用系统当前日期
        year, month, day = get_current_date()
        print(f"未指定日期，使用系统当前日期: {year}年{month}月{day}日")

    # 生成候选文件列表
    file_names = generate_file_names(year, month, day)
    url, file_name = find_latest_file(file_names)

    if url and file_name:
        download_file(url, file_name)
    else:
        print("未找到符合条件的Markdown文件")